package com.xiaoke.web.config;

import com.xiaoke.entity.Admin;
import com.xiaoke.utils.ValidUtil;
import com.xiaoke.web.config.shiro.CaptchaUsernamePasswordToken;
import com.xiaoke.web.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证
 *
 * @author lee
 * @date 2018-01-16 14:00
 */
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    //@Autowired
    //private UserRoleService userRoleService;

    /**
     * 授权(验证权限时调用) 暂无权限管理
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        Map map = new HashMap<>();
        map.put("username", username);
        List<Admin> users = adminService.findByParams(map);
        if (!ValidUtil.isEmpty(users)) {

        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        CaptchaUsernamePasswordToken captchaUPToken = (CaptchaUsernamePasswordToken) token;
        String username = (String) captchaUPToken.getPrincipal();
        Map map = new HashMap<>();
        map.put("username", username);
        List<Admin> users = adminService.findByParams(map);

//        账号锁定
        if (ValidUtil.isEmpty(users)) {
            throw new UnknownAccountException("账号不存在！");
        }
        Admin admin = users.get(0);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), ByteSource.Util.bytes(admin.getPasswordSalt()), getName());
        return info;
    }

}
